<?php
namespace app\model;

/**
 * Author: cbw
 * Desc: 投诉
 * Time: 2021/12/25 11:17 上午
 * Email: 17854288794@163.com
 */
class Complain{

    public static function getComplainList($system,$themeid,$status=0,$type='',$search='',$workerinfo='')
    {
        global $_G;
        $condition = "";
        if ($search) {
            $condition .= " AND a.nickname LIKE '" . $search . "'"
                . " or a.mobile LIKE '" . $search . "' "
                . " or a.content LIKE '" . $search . "'" . " or a.type LIKE '" . $search . "'";
        }
        if ($type) {
            $condition .= " and a.type='" . $type . "'";
        }
        if ($status==-1) {
            $condition .= " and a.status < 3";
        }elseif ($status) {
            $condition .= " and a.status=$status";
        }


        $condition .= $workerinfo . " ORDER BY a.status asc,a.id DESC";
        if($system['is_multiple_merchants']) {
            $shangjia_sql1 = ",s.name as companyname";
            $shangjia_sql2 = "left join " . tablename ( t_shangjia ) . " as s on w.company = s.id";
        }else{
            $shangjia_sql1 = ",'' as companyname";
        }
        $sql = " SELECT a.*,w.username as workername,t.name as teamname{$shangjia_sql1} FROM ". tablename(t_complain)." as a 
                left join " . tablename ( t_worker ) . " as w on a.workerid = w.uid and a.themeid = w.themeid 
                left join " . tablename ( t_team ) . " as t on w.team = t.id
                {$shangjia_sql2}
                WHERE a.software='".MODULE_NAME."' and  a.themeid=$themeid ".$condition;

        return db_select($sql);
    }

    public static function getTypeList($system,$themeid)
    {
        global $_P, $_G;
        $theme = Theme::getThemeById($themeid);
        $config =   Theme::getConfig($themeid);

        if ($_P['op']=='home' || $_P['op']=='homenewquestion'){
            $temp1 = [
                'title'=>'商家拒绝退款',
                'list'=>[['title'=>'','type'=>'txt','value'=>'']],
                'type'=>'input'
            ];
            $temp2 = [
                'title'=>'报名后无法联系商家',
                'list'=>[['title'=>'','type'=>'txt','value'=>'']],
                'type'=>'input'
            ];
            $temp3 = [
                'title'=>'虚假活动、活动不真实',
                'list'=>[['title'=>'','type'=>'txt','value'=>'']],
                'type'=>'input'
            ];
            $temp4 = [
                'title'=>'页面内含政治敏感、色情低俗、欺诈、违法、暴力',
                'list'=>[['title'=>'','type'=>'txt','value'=>'']],
                'type'=>'input'
            ];
            $temp5 = [
                'title'=>'页面内含造谣、传谣',
                'list'=>[['title'=>'','type'=>'txt','value'=>'']],
                'type'=>'input'
            ];
            $temp6 = [
                'title'=>'页面内含侵权、抄袭',
                'list'=>[['title'=>'','type'=>'txt','value'=>'']],
                'type'=>'input'
            ];
            $temp6 = [
                'title'=>'页面内含诱导分享',
                'list'=>[['title'=>'','type'=>'txt','value'=>'']],
                'type'=>'input'
            ];
            $temp7 = [
                'title'=>'其他',
                'list'=>[['title'=>'','type'=>'txt','value'=>'']],
                'type'=>'input'
            ];

            $content = [];
            array_push($content,$temp1);
            array_push($content,$temp2);
            array_push($content,$temp3);
            array_push($content,$temp4);
            array_push($content,$temp5);
            array_push($content,$temp6);
            array_push($content,$temp7);

            return ['title'=>'请选择投诉原因','content'=>$content,'info'=>""];
        }
        else if ($_P['op']=='question' || $_P['op']=='newquestion'){
            if (empty($_P['order_id'])){
                $themyrecord = Record::getLastPayRecord($_G['member']['uid'],$themeid);
            }else{
                $themyrecord = Record::getByIdUid($_G['member']['uid'],$_P['order_id']);
            }
            $worker=db_find("SELECT * FROM ".tablename(t_worker)." WHERE uid = '{$themyrecord['workerid']}'");
            $theme = Theme::updateThemeMobile($system,$theme,$worker['company']);
            if (!empty($theme['address'])){
                $addresstxt = $theme['address'];
            }elseif (!empty($config['addresstxt'])){
                $addresstxt = $config['province'] . $config['city'] .$config['district'] .$config['addresstxt'];
            }
            $jubf = empty($theme['jubf'])?mb_substr($theme['title'],0,12,'utf-8'):$theme['jubf'];
            $mobile = $theme['mobile'];

            $order_id = $themyrecord['id']+9000;
            $info=array(
                'worker_username'=>$worker['username'],
                'worker_avatar'=>$worker['avatar'],
                'worker_mobile'=>$worker['mobile'],
                'jubf'=>$jubf,
                'mobile'=>$mobile,
                'addresstxt'=>$addresstxt,
                'order'=>'定单号：' . $order_id . "<br>姓名：" . $themyrecord['username'] . " 电话：".substr_cut_mobile($themyrecord['mobile']) . "<br>金额：".$themyrecord['fee'] ." 付款时间：".date('Y-m-d H:i:s',$themyrecord['addtime'])
            );

            $temp1 = [
                'title'=>'如何联系商家？',
                'list'=>[
                    ['title'=>'您的专属客服：【'.$worker['username'].'】','type'=>'mobile','value'=>$worker['mobile']],
                    ['title'=>'商家：'.$jubf,'type'=>'txt','value'=>''],
                    ['title'=>empty($addresstxt)?'':'地址：'.$addresstxt,'type'=>'txt','value'=>''],
                    ['title'=>'电话：','type'=>'mobile','value'=>$mobile]
                ],
                'type'=>'dialog'
            ];

            $temp2 = [
                'title'=>'活动有无时间限制？',
                'list'=>[
                    ['title'=>'建议您查看首页活动详情中是否有介绍，或联系您的专属客服：【'.$worker['username'].'】','type'=>'mobile','value'=>$worker['mobile']]
                ],
                'type'=>'dialog'
            ];
            if (empty($worker)){
                $temp1['list']=[
                    ['title'=>'商家：'.$jubf,'type'=>'txt','value'=>''],
                    ['title'=>empty($addresstxt)?'':'地址：'.$addresstxt,'type'=>'txt','value'=>''],
                    ['title'=>'电话：','type'=>'mobile','value'=>$mobile]
                ];
                $temp2['list']=[
                    ['title'=>'建议您查看首页活动详情中是否有介绍，或联系客服','type'=>'mobile','value'=>$mobile]
                ];
            }
            $temp3 = [
                'title'=>'我暂时不需要了，如何申请退款？',
                'list'=>[
                    ['title'=>'活动是非常优惠的，建议先联系您的专属客服沟通确认；继续退款，请点击申请退款；','type'=>'txt','value'=>'']
                ],
                'type'=>'return'
            ];
            $temp4 = [
                'title'=>'我的奖金为什么未收到',
                'list'=>[
                    ['title'=>'请确认微信号是否实名认证或联系您的专属客服帮您查询','type'=>'txt','value'=>'']
                ],
                'type'=>'dialog'
            ];
            $temp5 = [
                'title'=>'如何核销定单',
                'list'=>[
                    ['title'=>'您需要持本手机到店，点击底部的我的定单，出示核销码，员工扫码即可','type'=>'txt','value'=>'']
                ],
                'type'=>'dialog'
            ];
            $temp6 = [
                'title'=>'投诉商家或工作人员',
                'list'=>[
                    ['title'=>'','type'=>'txt','value'=>'']
                ],
                'type'=>'input'
            ];
            $content = [];
            array_push($content,$temp1);
            array_push($content,$temp2);
            array_push($content,$temp3);
            array_push($content,$temp4);
            array_push($content,$temp5);
            array_push($content,$temp6);
            return ['title'=>'请问您遇到了什么问题？','content'=>$content,'info'=>$info];
        }else{
            $sql = " select `type` as title,count(*) as total from ".tablename(t_complain)." where software='".MODULE_NAME."' and themeid='".$themeid."' ";
            $list_new = db_select($sql);
            if (!empty($list_new)){
                foreach ($list_new as $index=>$item){
                    if ($item['total']==0){
                        unset($list_new[$index]);
                    }
                }
            }
            return $list_new;
        }
    }

    public static function getStatusList($themeid,$workerinfo)
    {
        $list = [
            ['status'=>0,'title'=>'所有','total'=>0],
            ['status'=>1,'title'=>'未处理','total'=>0],
            ['status'=>2,'title'=>'处理中','total'=>0],
            ['status'=>3,'title'=>'已完结','total'=>0],
        ];

        foreach ($list as $key => $val){
            $sql = " select count(*) as cnt from ".tablename(t_complain)." as a             
                left join " . tablename ( t_worker ) . " as w on a.workerid = w.uid and a.themeid = w.themeid 
                where a.software='".MODULE_NAME."' and a.themeid='".$themeid."' " .$workerinfo;
            if ($val['status']<>0){
                $sql .=" and a.status='".$val['status']."'";
            }
            $list[$key]['total'] = db_find($sql)['cnt'];
        }
        return $list;
    }
    public static function getComplain($fans,$themeid)
    {
        global $_P;
        if ($_P['op']!='newquestion' && $_P['op']!='homenewquestion'){
            $complain = db_find("select * from ".tablename(t_complain)."  WHERE software='".MODULE_NAME."' and themeid = ".$themeid." and uid = ".$fans['uid']." order by status asc,id desc");
            if (!empty($complain)) {
                if (empty($complain['reply_info'])) {
                    $complain['reply_info']=array();
                }else{
                    $complain['reply_info'] = unserialize($complain['reply_info']);
                }
            }
        }
        return $complain;
    }
    public static function saveComplain($system,$fans){
        global $_P,$_G;
        //op   display   save   请求方法
        $software = MODULE_NAME;//软件编号
        $themeid = intval($_P['themeid']);//活动id
        $type = trim($_P['type']);//投诉原因
        $desc = trim($_P['content']);//投诉描述
        $mobile = trim($_P['mobile']);//投诉人手机号

        if (empty($themeid)){
            return array('errcode'=>1,'errmsg'=>'活动id参数缺失');
        }

        //投诉提交保存
        $status = intval($_P['status']);
        if ($status==0){
            return  Complain::newComplainReply($system,$type,$desc,$mobile,$software,$themeid,$fans);
        }elseif ($status==2 || $status==3){
            if (!$desc && $status==2){
                return array('errcode'=>1,'errmsg'=>'请输入投诉描述');
            }
            $id = $_P['com_id'];
            $complain = db_get(t_complain,array('id'=>$id,'uid'=>$_G['member']['uid']));
            if (empty($complain)) {
                return array('errcode'=>1,'errmsg'=>'数据丢失');
            }else {
                if (!empty($complain['reply_info'])) {
                    $complain['reply_info'] = unserialize($complain['reply_info']);
                } else {
                    $complain['reply_info'] = array();
                }
            }
            if ($status==3){
                $tips = '系统';
            }else{
                $tips = '用户回复';
            }
            $_P['reply_txt']=$desc;
            Complain::saveComplainReply($system,$complain,$tips,$fans['nickname'],$status);
            if ($status==2) {
                return array('errcode'=>0,'errmsg'=>'您的回复信息我们已经收到，并会在48小时内受理');
            }else{
                return array('errcode'=>0,'errmsg'=>'您的反馈问题已完结，感谢您的理解与支持！');
            }

        }
    }
    public static function newComplainReply($system,$type,$desc,$mobile,$software,$themeid,$fans){
        global $_G;
        if (!$type){
            return array('errcode'=>1,'errmsg'=>'请选择投诉原因');
        }
        if (!$desc){
            return array('errcode'=>1,'errmsg'=>'请输入投诉描述');
        }
        if (!$mobile){
            return array('errcode'=>1,'errmsg'=>'请输入联系方式');
        }
        $validate = CheckPhoneNumber($mobile);
        if (!$validate){
            return array('errcode'=>1,'errmsg'=>'手机号格式错误');
        }
        $insert_data = [
            'uniacid' => $_G['mpid'],
            'software'=>$software,
            'themeid'=>$themeid,
            'type'=>$type,
            'content'=>$desc,
            'mobile'=>$mobile,
            'uid'=>$fans['uid'],
            'avatar'=>$fans['avatar'],
            'nickname'=>$fans['nickname'],
        ];
        $themyrecord = Record::getLastPayRecord($_G['member']['uid'],$themeid);
        if (!empty($themyrecord)){
            $insert_data['order_id'] = $themyrecord['id'];
            $insert_data['order_username'] = $themyrecord['username'];
            $insert_data['order_mobile'] = $themyrecord['mobile'];
            $insert_data['order_fee'] = $themyrecord['fee'];
            $insert_data['paytime'] = date('Y-m-d H:i:s',$themyrecord['addtime']);
            $insert_data['paystatus'] = $themyrecord['status'];
            $insert_data['workerid'] = $themyrecord['workerid'];
        }else{
            $insert_data['workerid'] = $fans['workerid'];
        }
        $insertid = db_insert(t_complain,$insert_data);
        $insert_data['id']= $insertid;
        $worker = Worker::getThemeWorkerByUid($insert_data['workerid'],$themeid,1);
        $insert_data['server_uid'] = $worker['qruserid'];
        $result = Poster::Getbanklist($system,'newComplain',$insert_data);

        $reply = Complain::getReplayType($type);
        if ($result['error']==1){
            db_delete(t_complain, array('id' => $insert_data['id']));
            return array('errcode'=>1,'errmsg'=>'保存失败，请重试');
        }else{
            return array('errcode'=>0,'errmsg'=>'您的反馈信息我们已经收到，并会在48小时内受理，请注意接听回电','reply'=>$reply);
        }
    }

    //问题需不需回复
    public static function getReplayType($type){
        return in_array($type, ["商家拒绝退款","报名后无法联系商家","申请退款","投诉商家或工作人员"]);
    }
    public static function saveComplainReply($system,$complain,$type,$username,$status=2,$update_data=array())
    {
        global $_P;
        $reply_txt = trim($_P['reply_txt']);
        if ($status==3 && $type=='系统'){
            $reply_txt .= "【用户确认问题已解决】：";
        }elseif ($status==3 ){
            $reply_txt .= "【关闭会话，已解决】";
        }
        $complain['reply_info'][] = array('type'=>$type,'opuser'=>$username,'reply'=>$reply_txt,'time'=>date("Y-m-d H:i:s"));

        $update_data['reply_info'] = serialize($complain['reply_info']);
        $update_data['status'] = $status;
        $update_data['updated_at'] = date("Y-m-d H:i:s");
        $res =  db_update(t_complain,$update_data,array('id'=>$complain['id'],'software' => MODULE_NAME,'themeid'=>$complain['themeid']));

        $insert_data =$update_data;
        $insert_data['id']=$complain['id'];
        $insert_data['software']=MODULE_NAME;
        $insert_data['themeid']=$complain['themeid'];
        $result = Poster::Getbanklist($system,'saveComplainReply',$insert_data);
        return $complain;
    }

    //超过2天自动更新为超时处理；
    public static function updateComplainReply($system,$themeid)
    {
        global $_P;
//        用户超时未确认
//        $time = date("Y-m-d H:i:s",strtotime("-2 day"));
//        $list = db_select("select * from ".tablename(t_complain)."  WHERE software='".MODULE_NAME."' and themeid = ".$themeid." and status=2 and updated_at < '".$time."'");
//        if (!empty($list)){
//            foreach ($list as $index => $item ){
//                $tips = '系统';
//                $_P['reply_txt'] = '用户超时未确认商家回复结果，投诉已完结';
//                if (!empty($item['reply_info'])) {
//                    $item['reply_info'] = unserialize($item['reply_info']);
//                } else {
//                    $item['reply_info'] = array();
//                }
//                Complain::saveComplainReply($system,$item, $tips, '系统',3);
//            }
//        }
        //状态  1待处理  2已处理 3待回访 4已回访
        $list = db_select("select c.* from ".tablename(t_complain)." as c
                left join " . tablename ( t_record ) . " as r on c.order_id = r.id and c.themeid = r.themeid 
                WHERE c.software='".MODULE_NAME."' and r.status=-1 and c.status<3");

        if (!empty($list)){
            foreach ($list as $index => $item ){
                $tips = '商家退款';
                $_P['reply_txt'] = '系统已退款，请在微信账单中查看';
                if (!empty($item['reply_info'])) {
                    $item['reply_info'] = unserialize($item['reply_info']);
                } else {
                    $item['reply_info'] = array();
                }
                $update_data = array(
                    'paystatus'=>'-1'
                );
                Complain::saveComplainReply($system,$item, $tips, '系统',3,$update_data);
            }
        }
    }

    public static function getDisplay($system,$themeid,$status,$type,$is_refund,$isweb=false){
        //每次调用时先更新状态；
        global  $_G,$_P;
        Complain::updateComplainReply($system,$themeid);

        $search_data =trim($_P['search_data']);
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }
        if (!$isweb){
            $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
            if ($myworker['level'] == '1') {
                $workerinfo="";
            } elseif ($myworker['level'] == '2') {
                $workerinfo = " and  w.company = '" . $myworker['company']."'";
            } else {
                $workerinfo = " and  a.workerid = '" . $myworker['uid']."'";
            }
        }

        $list = Complain::getComplainList($system,$themeid,$status,$type,$search_data,$workerinfo);
        $type_list = Complain::getTypeList($system,$themeid);
        $status_list = Complain::getStatusList($themeid,$workerinfo);
        $total = $page_total = count($list);

        if (!empty($list)){
            foreach ($list as $index=>$item){
                $record = Record::getById($item['order_id']);
                if (!empty($record) && $item['paystatus']!=$record['status']){
                    if ($record['status']==-1){
                        $update_data = array(
                            'paystatus'=>'-1',
                            'status'=>3,
                        );
                        db_update(t_complain,$update_data,array('id'=>$item['id']));
                    }else{
                        db_update(t_complain,array('paystatus'=>$record['status']),array('id'=>$item['id']));
                    }
                    $list[$index]['paystatus']=$record['status'];
                }
                if (!$is_refund && $item['type']=='申请退款'){
                    $list[$index]['type']='申请退款.';
                }
            }
        }
        return array(
            'list' =>$list,
            'type_list'=>$type_list,
            'status_list'=>$status_list,
            'total'=>$total,
        );
    }

    public static function chang_end($themeid){
        global $_P,$_G;
        $id = $_P['id'];
        $complain = db_get(t_complain,array('id'=>$id));
        if (is_array($complain)) {
            $reply_info = unserialize($complain['reply_info']);
        } else {
            $reply_info = array();
        }
        $reply_info[] = array('worker_info'=>$_G['username'],'reply'=>'已处理','time'=>date("Y-m-d H:i:s"));
        $update_data['reply_info'] = serialize($reply_info);
        $update_data['status'] = 2;
        $update_data['updated_at'] = date("Y-m-d H:i:s");
        $res =  db_update(t_complain,$update_data,array('id'=>$id,'software' => MODULE_NAME,'themeid'=>$themeid));
        return;
    }
    public static function reply($system,$id,$submit,$opuser,$is_refund){
        global $_G,$_P;
        $complain = db_get(t_complain,array('id'=>$id));
        if (!empty($complain['order_id'])){
            $record = Record::getById($complain['order_id']);
            if (!empty($record) && $complain['paystatus']!=$record['status']){
                if ($record['status']==-1){
                    $update_data = array(
                        'paystatus'=>'-1',
                        'status'=>3,
                    );
                    db_update(t_complain,$update_data,array('id'=>$complain['id']));
                }else{
                    db_update(t_complain,array('paystatus'=>$record['status']),array('id'=>$complain['id']));
                }
                $complain['paystatus']=$record['status'];
            }
            if (!$is_refund && $complain['type']=='申请退款'){
                $complain['type']='申请退款.';
            }
        }
        if (!empty($complain['reply_info'])) {
            $complain['reply_info'] = unserialize($complain['reply_info']);
        } else {
            $complain['reply_info'] = array();
        }
        if (empty($complain)) {
            return array('error'=>1,'msg'=>'未找到投诉编号');
        }
        if (checksubmit () || $_P['save']==true) {
            if (empty(trim($_P['reply_txt']))) {
                return array('error'=>1,'msg'=>'请输入需要回复的信息');
            }
            $tips = $_G['isSuperAdmin']?'平台管理员':'商家回复';
            if ($submit=='关闭会话' && $_G['isSuperAdmin']){
                $status = 3;
            }else{
                $status = 2;
            }
            $complain= Complain::saveComplainReply($system,$complain,$tips,$opuser,$status);
            return array('error'=>0,'msg'=>$status==2?'已回复，等待客户确认':'回复并关闭会话');
        }
        $complain['reply_info'] = array_reverse($complain['reply_info']);
        return $complain;
    }
    public static function refund($order_id,$id,$themeid,$theme,$system,$config,$opuser){
        global $_G;
        $ret = Record::refund($order_id,$themeid,$theme,$system,$config,$opuser);
        if ($ret['error']==0 || $ret['message']=="-2:订单已全额退款*OK") {
            if (intval($id) > 0) {
                $complain = db_get(t_complain, array('id' => $id));
                if (!empty($complain['reply_info'])) {
                    $complain['reply_info'] = unserialize($complain['reply_info']);
                } else {
                    $complain['reply_info'] = array();
                }
                $tips = $_G['isSuperAdmin'] ? '平台管理员退款' : '商家退款';
                $_P['reply_txt'] = '系统已退款，请在微信账单中查看';
                $update_data = array(
                    'paystatus'=>'-1'
                );
                $complain = Complain::saveComplainReply($system,$complain, $tips, $_G['username'],3,$update_data);
            }
        }
        return $ret;
    }
}